package com.xh3140.android.widget.dialog.view;

import android.content.Context;
import android.content.res.ColorStateList;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.RippleDrawable;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.AppCompatCheckBox;
import androidx.recyclerview.widget.RecyclerView;

import com.xh3140.android.widget.dialog.params.ItemParams;
import com.xh3140.android.widget.dialog.utils.DrawableUtils;
import com.xh3140.android.widget.dialog.utils.LayoutParamsBuilder;
import com.xh3140.android.widget.dialog.utils.ViewUtils;

public class ItemView extends AppCompatCheckBox {
    private boolean mIsSingle;
    private final Drawable mDrawableSingle;
    private final Drawable mDrawableMultiple;

    private ItemView(@NonNull Context context) {
        super(context);
        mDrawableSingle = DrawableUtils.android(getContext(), android.R.attr.listChoiceIndicatorSingle);
        mDrawableMultiple = DrawableUtils.android(getContext(), android.R.attr.listChoiceIndicatorMultiple);
    }

    public ItemView(@NonNull Context context, boolean isSingle, boolean isRight) {
        this(context);
        mIsSingle = isSingle;
        final Drawable drawable = mIsSingle ? mDrawableSingle : mDrawableMultiple;
        if (!isRight) {
            setButtonDrawable(drawable);
        } else {
            setButtonDrawable(null);
            setCompoundDrawablesRelativeWithIntrinsicBounds(null, null, drawable, null);
        }
    }

    /**
     * 配置视图
     *
     * @param params 列表项目视图配置属性
     */
    public void configView(@NonNull ItemParams params) {
        setChecked(params.isChecked);
        setText(params.text);
        setTextSize(params.textSize);
        setTextColor(params.textColor);
        setTypeface(getTypeface(), params.typeface);
        setGravity(params.gravity);
        if (params.backgroundColor != 0) {
            setBackgroundColor(params.backgroundColor);
        } else {
            setBackground(new RippleDrawable(ColorStateList.valueOf(0x1F000000), null, new ColorDrawable(0xFFFFFFFF)));
        }
        ViewUtils.setPaddingRelative(this, params.padding);
        setLayoutParams(LayoutParamsBuilder.ofMW(RecyclerView.LayoutParams.class)
                .setMarginsRelative(params.margins)
                .build());
        ViewUtils.setTextViewHeight(this, params.height);
        if (params.callback != null) {
            params.callback.callback(this);
        }
    }

    @Override
    public void toggle() {
        if (mIsSingle) {
            if (!isChecked()) {
                super.setChecked(true);
            }
        } else {
            super.toggle();
        }
    }
}
